/**
 * @description : 区域模块
 */
const regionModel = require('../models/regionModel');
const qs = require("qs")

/**
 * 
 * @param {Express.Request} req 
 * @param {Express.Response} res 
 */
const regionList = async (req, res) => {
    try {
        const { body } = req;
        const tmpRequest = body ? qs.parse(body) : {};
        const tmpMatch = { status: 1 };

        if (tmpRequest.searchForm) {
            const { searchVal } = JSON.parse(tmpRequest.searchForm);
            if (searchVal) {
                const regVal = new RegExp(searchVal, "i");
                tmpMatch.$or = [
                    { province_code: { $regex: regVal } },
                    { province_name: { $regex: regVal } }
                ];
            }
        }

        const [countResult] = await regionModel.aggregate([
            { $match: tmpMatch },
            { $count: "count" }
        ]);

        const count = countResult ? countResult.count : 0;
        let list = [];

        if (count > 0) {
            const page = parseInt(tmpRequest.page, 10) || 1;
            const pageSize = parseInt(tmpRequest.pageSize, 10) || 10;
            const skip = (page - 1) * pageSize;
            
            list = await regionModel.aggregate([
                    { $match: tmpMatch },
                    { $project: { _id: 0, province_code: 1, province_name: 1, create_time: 1 } },
                    { $skip: skip },
                    { $limit: pageSize }
            ]);
        }

        res.sendSuccess({ count, list });
    } catch (error) {
        console.error(error);
        res.sendFailure(`操作错误: ${error.message}`, 2, error);
    }
};

module.exports = { regionList }